package com.feiyu.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Recv {

	private static final String QUEUE_NAME = "hello";

	public static void recv() throws IOException, TimeoutException {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		// 这里不使用try-with-resource，因为需要保持活动状态持续监听
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		// 这里也声明队列，保证无论是发布者还是消费者，在连接之前队列已经存在
		// 消费的队列名应与发布的命名相匹配
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		System.out.println(" [*] 等待消息");
		// 服务器异步推送消息过来，这里以接口的对象形式提供回调，用于处理消息
		DeliverCallback deliverCallback = (consumerTag, delivery) -> {
			String message = new String(delivery.getBody(), "UTF-8");
			System.out.println(" [x] 接收消息 '" + message + "'");
		};
		channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});
	}
}
